<?php
/* @var $this DemandeController */
/* @var $model Demande */
/* @var $form CActiveForm */
$cs = Yii::app()->getClientScript();
$cs->registerScript('form_demande', "
		
	$('#optionsIdtype1').change(function() { choix_type(1); $('#Demande_grain').attr('placeholder','saisissez le nom d\'un objet')});
	$('#optionsIdtype2').change(function() { choix_type(2); $('#Demande_grain').attr('placeholder','saisissez le nom d\'un service')});
		
	function choix_type(type) {
		if ($('#Type_id').val() != type) { $('#Type_id').val(type); }
		if (!$('#demande_etape_deux').is(\":visible\")) { $('#demande_etape_deux').show(); }
		$('#Demande_grain').val('');
		toggle_valide_grain();
		remove_selistes();
		if ($('#Type_id').val() == 1) {
			$('#warning_type_grain').html('cet objet');
			$('#ajout_grain_domaine').html('Domaine de l\'objet');
			$('#ajout_grain_descr').html('Description de l\'objet');
			$('#Grain_descr').attr('placeholder','Saisissez la decription de l\'objet (facultatif)');
		} else {
			$('#warning_type_grain').html('cet service');
			$('#ajout_grain_domaine').html('Domaine du service');
			$('#ajout_grain_descr').html('Description du service');
			$('#Grain_descr').attr('placeholder','Saisissez la decription du service (facultatif)');
		}
		$('#Demande_grain').focus();
	}
		
	// constructs the suggestion engine
	var grains = new Bloodhound({
		remote: {
			url : '" . $this->createUrl("grain/getGrains") . "&nom=%QUERY',
			replace: function () {
            	var q = '" . $this->createUrl("grain/getGrains") . "&type='+$('#Type_id').val()+'&nom='+$('#Demande_grain').val();
                return q;
        	}
		},
		limit: 20,
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace
	});
	 
	grains.initialize();
	 
	$('#bloodhound .typeahead').typeahead({
	  hint: true,
	  highlight: true,
	  minLength: 1
	},
	{
	  displayKey: 'value',
	  source: grains.ttAdapter(),
	  templates: {
	  	suggestion: Handlebars.compile('<p>{{value}} <em><small class=\"pull-right nostrong\">{{domaine}}</small></em></p>')
      }
	});
		
	function toggle_valide_grain() {
		grainval = $('#Demande_grain').val();
		if (grainval.length > 1) {
			$('#valide_grain').show();
		} else {
			$('#valide_grain').hide();
		}
	}
		
	$('#Demande_grain').keyup(function() {
		toggle_valide_grain();
	});
		
	$('#Demande_grain').change(function() {
		toggle_valide_grain();
	});
		
	$('#bloodhound').bind('typeahead:selected', function(obj, datum, name) {
		toggle_valide_grain();
    });	
		
	$('#bloodhound').bind('typeahead:autocompleted', function(obj, datum, name) {
		toggle_valide_grain();
    });	
		
	function check_grain(grain,type) {
		$.ajax({
			url: '" . Yii::app()->createUrl("grain/checkGrain") . "',
			type: 'get',
        	data: {nom: grain, type:type},
			success:function(data) {
				if (data>0) {
					$('#Demande_idgrain').val(data);
					valide_etape_deux(grain,type);
					check_selistes(data);
				} else {
					ajoute_grain(grain,type);
					$('#Demande_idgrain').val(0);
					return false;
				}
			},
		});
	}
		
	$('#valide_grain').click(function() {
		check_grain($('#Demande_grain').val(),$('#Type_id').val());
	});
		
	function valide_etape_deux(grain, type) {
		$('#optionsIdtype1').prop('disabled', true);
		$('#optionsIdtype2').prop('disabled', true);
		$('#label_optionsIdtype1').removeClass('btn-primary').addClass('disabled btn-success');
		$('#label_optionsIdtype2').removeClass('btn-primary').addClass('disabled btn-success');
		$('#Demande_grain').prop('disabled', true);
		$('#demande_etape_un').addClass('has-success');
		$('#feedback_grain_ok').show();
		$('#demande_etape_deux').addClass('has-success has-feedback');
		$('#valide_grain').hide();
		$('#divmodif_grain').show();
		$('#demande_etape_trois').show();
		$('#demande_etape_quatre').show();
		$('#validedemande').html('Valider la demande');
	}

	function ajoute_grain(grain, type) {
		$('#optionsIdtype1').prop('disabled', true);
		$('#optionsIdtype2').prop('disabled', true);
		$('#label_optionsIdtype1').removeClass('btn-primary').addClass('disabled btn-warning');
		$('#label_optionsIdtype2').removeClass('btn-primary').addClass('disabled btn-warning');
		$('#Demande_grain').prop('disabled', true);
		$('#demande_etape_un').addClass('has-warning');
		$('#feedback_grain_warning').show();
		$('#demande_etape_deux').addClass('has-warning has-feedback');
		$('#valide_grain').hide();
		$('#divmodif_grain').show();
		$('#demande_etape_deux_creer').show();
		$('#demande_etape_trois').show();
		if ($('input[name=\'Grain[iddomaine]\']:checked').val()>0) $('#demande_etape_quatre').show();
		if ($('#Type_id').val() == 1) {
			$('#validedemande').html('Valider la demande et ajouter l\'objet au catalogue');
		} else {
			$('#validedemande').html('Valider la demande et ajouter le service au catalogue');
		}
	}
	
	$('input[name=\'Grain[iddomaine]\']').change(function() {
		$('#demande_etape_quatre').show();
	});

	$('#modif_grain').click(function() {
		$('#optionsIdtype1').prop('disabled', false);
		$('#optionsIdtype2').prop('disabled', false);
		$('#label_optionsIdtype1').removeClass('btn-success btn-warning disabled').addClass('btn-primary');
		$('#label_optionsIdtype2').removeClass('btn-success btn-warning disabled').addClass('btn-primary');
		$('#Demande_grain').prop('disabled', false);
		$('#demande_etape_un').removeClass('has-success has-warning');
		$('#feedback_grain_ok').hide();
		$('#feedback_grain_warning').hide();
		$('#demande_etape_deux').removeClass('has-success has-warning has-feedback');
		$('#valide_grain').show();
		$('#demande_etape_deux_creer').hide();
		$('#divmodif_grain').hide();
		$('#demande_etape_trois').hide();
		$('#demande_etape_trois_options').hide();
		$('#options_angle').removeClass('fa-angle-down').addClass('fa-angle-right');
		$('#demande_etape_quatre').hide();
		remove_selistes();
	});
		
	$('#btn_options').hover(
		function() {
    		$('#options_spin').addClass('fa-spin');
  		}, function() {
    		$('#options_spin').removeClass('fa-spin');
 	 	}
	);
		
	$('#btn_options').click(function(){
		if ($('#options_angle').hasClass('fa-angle-right')) {
			$('#demande_etape_trois_options').show();
			$('#options_angle').removeClass('fa-angle-right').addClass('fa-angle-down');
			return false;
		} else {
			$('#demande_etape_trois_options').hide();
			$('#options_angle').removeClass('fa-angle-down').addClass('fa-angle-right');
			return false;
		}
	});
		
	function check_selistes(idgrain) {
		$.ajax({
			url: '" . Yii::app()->createAbsoluteUrl("seliste/getSelistesGrain") . "',
			type: 'get',
        	datatype: 'json',
			data: {
				id: idgrain,
			},
			success:function(data) {
           		var selistes = JSON.parse(data);
				var toAppend = '';
				var toAppendSelistes = '';
		    	var nbselistes = 0;
				$.each(selistes, function (k,v) {
					nbselistes++;
					toAppendSelistes += '<option value=\''+v.id+'\'>'+v.seliste+'</option>';
				});
				if (nbselistes>0) {
					if ($('#Type_id').val() == 1) {
						toAppend += '<option value=\'-1\'>Seulement les sélistes proposant l\'objet</option>';
					} else {
						toAppend += '<option value=\'-1\'>Seulement les sélistes proposant le service</option>';
					}
				}
				toAppend += '<option value=\'0\'>Tous les sélistes</option>';
				toAppend += toAppendSelistes;
				if (nbselistes>0) {
					$('#Demande_idseliste_cible').attr('multiple','multiple');
					$('#Demande_idseliste_cible').removeAttr('disabled');
				}
				$('#Demande_idseliste_cible').empty().append(toAppend);
				$('#Demande_idseliste_cible').multiselect('destroy');
				$('#Demande_idseliste_cible').multiselect({
					checkboxName: 'destinataires[]',
					enableFiltering:true,
					enableCaseInsensitiveFiltering: true,
					filterPlaceholder:'Rechercher un destinataire',
					maxHeight:400,
					nonSelectedText:'Choisir un (ou des) destinataire(s)',
					nSelectedText:' destinataires sélectionnés',
					onChange: function(option, checked) {
						var values = [];
						var nb=0;
      					if ((option[0].value==0 || option[0].value==-1) && checked) {
							$('#Demande_idseliste_cible option').each(function() {
								if ($(this).val() !== option.val()) {
									values.push($(this).val());
								}
							});
							$('#Demande_idseliste_cible').multiselect('deselect', values);
						} else if (option[0].value>0 && checked) {
							values.push(0);
							if (nbselistes>0) values.push(-1);
							$('#Demande_idseliste_cible').multiselect('deselect', values);
						} else {
							$('#Demande_idseliste_cible option').each(function() {
								if ($(this).attr('selected') == 'selected') {
									nb++;
								}
							});
							if (nb == 0) {
								if (nbselistes>0) {
									$('#Demande_idseliste_cible').multiselect('select',-1);
								} else {
									$('#Demande_idseliste_cible').multiselect('select',0);
								}
							}
						}
      				}
	  			});
				if (nbselistes>0) {
					$('#Demande_idseliste_cible').multiselect('select',-1);
				} else {
					$('#Demande_idseliste_cible').multiselect('select',0);
				}
			},
		});
	}
		
	function remove_selistes() {
		$('#Demande_idseliste_cible').empty().append('<option value=\'0\' selected=\'selected\'>Tous les sélistes</option>');
		$('#Demande_idseliste_cible').removeAttr('multiple');
		$('#Demande_idseliste_cible').attr('disabled','disabled');
		$('#Demande_idseliste_cible').multiselect('destroy');
	}
		
	function valide_form(form) {
		$('#optionsIdtype1').prop('disabled', false);
		$('#optionsIdtype2').prop('disabled', false);
		$('#Demande_grain').prop('disabled', false);
	}
		
",CClientScript::POS_END );
?>

<div class="form">

<?php 
$form=$this->beginWidget('CActiveForm', array(
		'id'=>'demande-form',
		'htmlOptions'=>array('class'=>'form-horizontal','onSubmit'=>'return valide_form(this)'),
		'enableAjaxValidation'=>false,
));
?>

    <?php $labels = $model->attributeLabels();?>

	<?php echo $form->errorSummary($model,NULL,NULL,array("class"=>"alert alert-danger")); ?>
	
	<?php echo $form->hiddenField($model,'status',array("value"=>1)); ?>
	<?php echo $form->hiddenField($model,'idseliste',array("value"=>Yii::app()->user->id)); ?>
	<?php echo $form->hiddenField($model->type,'id',array("value"=>0)); ?> 
	<?php echo $form->hiddenField($model,'idgrain',array("value"=>0)); ?> 
	
	<?php $types = Type::model()->findAll(array('order'=>'lib asc'));?>
	<?php $domaines = Domaine::model()->findAll(array('order'=>'lib asc'));?>
	
	
	<div id="demande_etape_un" class="form-group form-group-lg">
		<label class="col-lg-4 control-label">Je sollicite</label>
		<div class="col-lg-8">
			<div id="radio_type" class="btn-group" data-toggle="buttons">
				<label id="label_optionsIdtype1" class="btn btn-primary<?php if ($model->type->id == 1) echo " active";?>">
					<?php echo $form->radioButton($model->type,'id',array("id"=>"optionsIdtype1","name"=>"Demande[type][id]","uncheckValue"=>NULL,"value"=>1)); ?> un prêt d'objet
				</label>
				<label id="label_optionsIdtype2" class="btn btn-primary<?php if ($model->type->id == 2) echo " active";?>">
					<?php echo $form->radioButton($model->type,'id',array("id"=>"optionsIdtype2","name"=>"Demande[type][id]","uncheckValue"=>NULL,"value"=>2)); ?> un service
				</label>
			</div>
		</div>
	</div>
	
	<div id="demande_etape_deux" class="form-group form-group-lg">
		<label class="col-lg-4 control-label">Je recherche</label>
		<div id="bloodhound" class="col-lg-6">
			<input type="text" id="Demande_grain" name="Demande_grain" class="form-control typeahead" placeholder="ma recherche">
			<span id="feedback_grain_ok" class="glyphicon glyphicon-ok form-control-feedback"></span>
			<span id="feedback_grain_warning" class="glyphicon glyphicon-warning-sign form-control-feedback"></span>
		</div>
		<div class="col-lg-2">
			<button type="button" id="valide_grain" class="btn btn-primary btn-block"><span class="fa fa-check-square-o"></span> Valider</button>
		</div>
		<div class="col-lg-2" id="divmodif_grain">
			<button type="button" id="modif_grain" class="btn btn-default btn-block"><span class="fa fa-edit"></span> Modifier</button>
		</div>
	</div>
	<div id="demande_etape_deux_creer">
		<div class="col-lg-8 col-lg-offset-4">
			<p class="bg-warning text-warning"><span class="glyphicon glyphicon-warning-sign"></span> Attention : <span id="warning_type_grain"></span> ne figure pas dans le catalogue. Il sera ajouté lors de la confirmation de votre demande<?php if (Yii::app()->user->admin == 0) echo " et devra être validé par un administrateur";?>.</p>
		</div>		
		<div class="form-group form-group-lg<?php if ($model->getErrors('domaine')) echo " has-error";?>">
			<?php $modelgrain = new Grain;?>
			<?php echo $form->hiddenField($modelgrain,'idseliste',array("value"=>Yii::app()->user->id)); ?>
			<?php echo $form->hiddenField($modelgrain,'status',array("value"=>Yii::app()->user->admin ? 1 : 0)); ?>
			<label  id="ajout_grain_domaine" class="col-lg-4 control-label">Domaine</label>
			<div class="col-lg-8">
				<div class="btn-group" data-toggle="buttons">
					<?php 
					$domaines = Domaine::model()->findAll(array('order'=>'lib asc'));
					$d = 0;
					foreach ($domaines as $domaine) {
						?>
						<label class="btn btn-primary">
							<?php echo $form->radioButton($modelgrain,'iddomaine',array("id"=>"optionsDomaine".$d,"uncheckValue"=>NULL,"value"=>$domaine->id)) . $domaine->lib; ?> 
						</label>
						<?php
						$d++; 	
					}
					?>
				</div>
			</div>
		</div>       
        <div class="form-group form-group-lg<?php if ($modelgrain->getErrors('descr')) echo " has-error";?>">
                <label id="ajout_grain_descr" class="col-lg-4 control-label"></label>
                <div class="col-lg-8"><?php echo $form->textArea($modelgrain,'descr',array("class"=>"form-control","placeholder"=>"Saisir la description")); ?></div>
        </div>
	</div>
	
	<div id="demande_etape_trois" class="form-group form-group-lg">
		<div class="col-lg-5 col-lg-offset-4">
			<button type="button" id="btn_options" class="btn btn-default" data-toggle="tooltip" data-placement="right" data-container="body" data-title="ajouter un commentaire, choisir les destinataires, le mode de contact"><span id="options_spin" class="fa fa-cog"></span> Options <span id="options_angle" class="fa fa-angle-right"></span></button>
			<?php $cs->registerScript('tooltip', "$('#btn_options').tooltip();",CClientScript::POS_READY);?>
		</div>
	</div>
	
	<div id="demande_etape_trois_options">		
		<div class="form-group form-group-lg<?php if ($model->getErrors('commentaire')) echo " has-error";?>">
			<?php echo $form->labelEx($model,'commentaire',array("class"=>"col-lg-4 control-label")); ?>
			<div class="col-lg-8"><?php echo $form->textArea($model,'commentaire',array("class"=>"form-control","placeholder"=>"Saisir un commentaire éventuel sur votre demande")); ?></div>
		</div>
		<div class="form-group form-group-lg">
		    <label class="col-lg-4 control-label">Solliciter</label>
		    <div class="col-lg-8">
			    <select id="Demande_idseliste_cible" class="form-control multiselect" multiple="multiple"></select>
		    </div>
		</div>
		<div id="form-group-mode" class="form-group<?php if ($model->getErrors('modecontact')) echo " has-error";?>">
			<?php echo $form->label($model,'modecontact',array("class"=>"col-lg-4 control-label")); ?>
			<div class="col-lg-8">
				<div class="btn-group" data-toggle="buttons">
					<label class="btn btn-primary<?php if ($model->modecontact == 0) echo " active";?>">
						<?php echo $form->radioButton($model,'modecontact',array("id"=>"optionsModecontact0","name"=>"Demande[modecontact]","uncheckValue"=>NULL,"value"=>0)); ?> Messagerie interne
					</label>
					<label class="btn btn-primary<?php if ($model->modecontact == 1) echo " active";?>">
						<?php echo $form->radioButton($model,'modecontact',array("id"=>"optionsModecontact1","name"=>"Demande[modecontact]","uncheckValue"=>NULL,"value"=>1)); ?> Email
					</label>
					<label class="btn btn-primary<?php if ($model->modecontact == 2) echo " active";if (($seliste->telfixe == '') || ($seliste->v_telfixe == 0)) echo " disabled";?>">
						<?php 
						if (($seliste->telfixe == '') || ($seliste->v_telfixe == 0)) {
							echo $form->radioButton($model,'modecontact',array("id"=>"optionsModecontact2","name"=>"Demande[modecontact]","uncheckValue"=>NULL,"value"=>2,"disabled"=>"disabled"));
						} else {
							echo $form->radioButton($model,'modecontact',array("id"=>"optionsModecontact2","name"=>"Demande[modecontact]","uncheckValue"=>NULL,"value"=>2));
						}
						?> Téléphone fixe
					</label> 
					<label class="btn btn-primary<?php if ($model->modecontact == 3) echo " active";if (($seliste->telport == '') || ($seliste->v_telport == 0)) echo " disabled";?>">
						<?php 
						if (($seliste->telport == '') || ($seliste->v_telport == 0)) {
							echo $form->radioButton($model,'modecontact',array("id"=>"optionsModecontact3","name"=>"Demande[modecontact]","uncheckValue"=>NULL,"value"=>3,"disabled"=>"disabled"));
						} else {
							echo $form->radioButton($model,'modecontact',array("id"=>"optionsModecontact3","name"=>"Demande[modecontact]","uncheckValue"=>NULL,"value"=>3));
						}
						?> Téléphone portable
					</label>
				</div>
			</div>
		</div>
	</div>
	
	<div id="demande_etape_quatre" class="form-group form-group-lg">
		<div class="col-lg-offset-4 col-lg-8">
			<button type="submit" id="btn_validedemande" class="btn btn-primary btn-lg"><span class="fa fa-check-square-o"></span> <span id="validedemande">Valider la demande</span></button>
		</div>
	</div>
	
	


<?php $this->endWidget(); ?>

</div>
<!-- form -->